package com.example.andylau96.res.Function.Cashier;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.method.NumberKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.andylau96.res.DataBase.CashierDataBase;
import com.example.andylau96.res.Main.MainActivity;
import com.example.andylau96.res.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by AndyLau96 on 2016/12/18.
 */
public class checkFragment extends Fragment implements View.OnClickListener,AdapterView.OnItemClickListener
{

    private LinearLayout title;
    private ImageButton re;
    private Button ok;
    private ListView check_list;
    private TextView v,x,check_ID,people,accounts;
    private EditText text;
    private SQLiteDatabase db;
    private int checkID=1;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.check,container,false);
        re= (ImageButton) view.findViewById(R.id.check_title_return);
        ok= (Button) view.findViewById(R.id.check_title_ok);
        title= (LinearLayout) view.findViewById(R.id.check_title);
        check_list= (ListView) view.findViewById(R.id.check_list);
        check_ID= (TextView) view.findViewById(R.id.check_id);
        people= (TextView) view.findViewById(R.id.check_people);
        accounts= (TextView) view.findViewById(R.id.check_accounts);
        re.setOnClickListener(this);
        ok.setOnClickListener(this);
        check_list.setOnItemClickListener(this);
        SimpleAdapter adapter=new SimpleAdapter(getActivity(),getData(),R.layout.choose_food_item,new String[]{"name","price","num"},new int[]{
        R.id.food_name,R.id.food_price,R.id.food_num});
        check_list.setAdapter(adapter);
        return view;
    }

    public List<Map<String,Object>> getData()
    {
        List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
        db=new CashierDataBase(getActivity().getApplication()).getWritableDatabase();
        Cursor re=db.rawQuery("select *from ConsumeItem",null);
        String name[]=new String[100];
        double price[]=new double[100];
        int i=0;
        re.moveToFirst();
        while(!re.isAfterLast()) {
            name[i] = re.getString(re.getColumnIndex("itemName"));
            price[i] = re.getDouble(re.getColumnIndex("itemPrice"));
            Map<String,Object> map=new HashMap<>();
            map.put("name",name[i]);
            map.put("price",price[i]);
            map.put("num","0");
            list.add(map);
            i++;
            re.moveToNext();
        }
        re.close();
        db.close();
        return list;
    }
    @Override
    public void onClick(View view) {
        int id=view.getId();
        if(id==R.id.check_title_ok)
        {
            String mid=check_ID.getText().toString();
            String mpeo=people.getText().toString();
            String account=accounts.getText().toString();
            String food="";
            LinearLayout n= (LinearLayout) check_list.getChildAt(0);
            int i=0;
            while(n!=null)
            {
                TextView tv= (TextView) n.findViewById(R.id.food_num);
                food+=tv.getText().toString()+"-";
                i++;
                n= (LinearLayout) check_list.getChildAt(i);
            }
            if(mid.length()==0||mpeo.length()==0||account.length()==0)
            {
                Toast.makeText(getActivity(), "请输入完整的登记信息", Toast.LENGTH_SHORT).show();
            }
            else
            {
                db=new CashierDataBase(getActivity().getApplication()).getWritableDatabase();
                db.execSQL("insert into DinningInfo values('"+mid+"',"+mpeo+",'"+food+"',"+account+")");
                db.close();
                checkID++;
                String p=checkID+"";
                try {
                    FileOutputStream crate = getActivity().openFileOutput("checkid.txt", getActivity().MODE_PRIVATE);
                    crate.write(p.getBytes());
                    crate.close();
                    Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                }
                getFragmentManager().popBackStack();
            }
        }
        if(id==R.id.check_title_return)
        {
            getFragmentManager().popBackStack();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        v= (TextView) view.findViewById(R.id.food_num);
        x= (TextView) view.findViewById(R.id.food_price);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        text = new EditText(getActivity());
        text.setKeyListener(new NumberKeyListener() {
            @Override
            protected char[] getAcceptedChars() {
                return new char[]{'0','1','2','3','4','5','6','7','8','9'};
            }

            @Override
            public int getInputType() {
                return 0;
            }
        });
        builder.setTitle("请输入订购数量");
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setView(text);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String number=text.getText().toString();
                if(number.length()==0)
                    Toast.makeText(checkFragment.this.getActivity(), "请输入订购数量", Toast.LENGTH_SHORT).show();
                else
                {
                    v.setText(number);
                    double sum=Double.valueOf(accounts.getText().toString());
                    int num=Integer.valueOf(number);
                    double price=Double.valueOf(x.getText().toString());
                    sum=sum+price*num;
                    accounts.setText(sum+"");
                    dialogInterface.dismiss();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }

    @Override
    public void onStart() {
        super.onStart();
        MainActivity.now=this;
        String theme=null;
        File file=new File("/data/data/com.example.andylau96.res/files/color.txt");
        try {
            InputStreamReader reader=new InputStreamReader(new FileInputStream(file),"UTF-8");
            BufferedReader br=new BufferedReader(reader);
            theme="";
            String temp=null;
            while((temp=br.readLine())!=null)
            {
                theme+=temp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        title.setBackgroundColor(Color.parseColor(theme));

        File f=new File("/data/data/com.example.andylau96.res/files/checkid.txt");
        String t="";
        try {
            InputStreamReader reader=new InputStreamReader(new FileInputStream(f),"UTF-8");
            BufferedReader br=new BufferedReader(reader);
            String temp=null;
            while((temp=br.readLine())!=null)
            {
                t+=temp;
            }
            checkID=Integer.valueOf(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        check_ID.setText(checkID+"");
    }
}
